#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: twl
@date: 2020/5/9 11:25
@description:
"""
import datetime


class BaseModel(object):
	def to_json(self):
		fields = self.__dict__
		if "_sa_instance_state" in fields:
			del fields["_sa_instance_state"]
		for key, value in fields.items():
			if isinstance(
				value,
				list) and len(value) > 0 and (isinstance(
				value[0],
				BaseModel)):
				fields[key] = BaseModel.__list_2_json(value)
			elif isinstance(value, BaseModel):
				fields[key] = value.to_json()
			elif isinstance(value, datetime.datetime):
				fields[key] = value.strftime('%Y-%m-%d %H:%M:%S')
			elif isinstance(value, datetime.time):
				fields[key] = value.isoformat()
			elif isinstance(value, datetime.timedelta):
				fields[key] = (
					datetime.datetime.min +
					value).time().isoformat()
		return fields

	@staticmethod
	def __list_2_json(value):
		result = []
		for item in value:
			result.append(item.to_json())
		return result
